package com.ruoyi.system.controllerApi;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.system.domain.Orders;
import com.ruoyi.system.domain.Tickets;
import com.ruoyi.system.service.IOrdersService;
import com.ruoyi.system.service.ITicketsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.util.ObjectUtils;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/tickets")
public class TicketsApiController {

    @Autowired
    private ITicketsService ticketsService;
    @Autowired
    private IOrdersService ordersService;

    /**
     * 查询列表
     */
    @GetMapping("/list")
    public AjaxResult list(Tickets tickets) {
        List<Map<String, Object>> list = ticketsService.selectTicketsList2(tickets);
        return AjaxResult.success(list);
    }


    /**
     * 查询订单详情
     */
    @GetMapping("/orderList")
    public AjaxResult orderList(Integer userId) {
        List<Map<String, Object>> list = ordersService.selectOrderByUserId(userId);
        return AjaxResult.success(list);
    }

    /**
     * 买票
     */
    @PostMapping("/buy")
    public AjaxResult buy(
                          @RequestParam(name = "userId") Long userId,
                          @RequestParam(name = "ticketId") Long ticketId,
                          @RequestParam(name = "yyDate") String yyDate,
                          @RequestParam(name = "count") Integer count) {
//        Integer count = orders.getCount();
//        Long ticketId = orders.getTicketId();
        if (ObjectUtil.isEmpty(count) || ObjectUtil.isEmpty(ticketId) || ObjectUtil.isEmpty(yyDate) || ObjectUtil.isEmpty(userId)){
            return AjaxResult.error("参数错误");
        }
        Orders orders = new Orders();
        Tickets tickets = ticketsService.selectTicketsById(ticketId);
        BigDecimal price = tickets.getPrice();
        BigDecimal multiply = price.multiply(new BigDecimal(count));
        orders.setAmount(multiply);
        orders.setUserId(userId);
        orders.setTicketId(ticketId);
        orders.setCount(count);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date date = dateFormat.parse(yyDate);
            orders.setYyDate(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        orders.setOrderDate(new Date());
        return AjaxResult.success(ordersService.insertOrders(orders));
    }

    /**
     * 退票
     */
    @DeleteMapping("/refund")
    public AjaxResult refund(Long id) {
        return AjaxResult.success(ordersService.deleteOrdersById(id));
    }
}
